package com.itheima.pinda.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.apache.commons.lang3.ObjectUtils;

import java.util.Map;

public class HttpUtils {

    private static final ObjectMapper mapper = new ObjectMapper();


    /**
     * 发送get请求
     *
     * @param url url
     * @param params 无参数传递null
     * @return
     */
    public static String sendHttpGet(String url, Map<String,String> params) throws Exception{

        HttpRequest request = HttpRequest.get(url);

        if (ObjectUtils.isNotEmpty(params)){
            request.query(params);
        }

        HttpResponse response = request.send();
        String bodyText = response.bodyText();

        String text = transFormToUtf8(bodyText);
        return text;
    }

    /**
     * 发送json数据格式的post请求
     * @param url
     * @param params 无参数传递null
     * @return
     */
    public static String sendPostJson(String url, Map<String,Object> params){
        HttpRequest request = HttpRequest.get(url);
        request.contentType("application/json");
        request.charset("utf-8");

        if (ObjectUtils.isNotEmpty(params)){
            try {
                request.body(mapper.writeValueAsString(params));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        HttpResponse response = request.send();
        return response.bodyText();
    }

    /**
     * 发送表单格式的post请求
     *
     * @param url
     * @param params 无参数传递null
     * @return
     */
    public static String sendHttpPost(String url, Map<String, Object> params){
        HttpRequest request = HttpRequest.get(url);

        if (ObjectUtils.isNotEmpty(params)){
            request.form(params);
        }

        HttpResponse response = request.send();
        return response.bodyText();
    }

    /**
     * 字符串转换为utf-8输出
     * @param source
     * @return
     */
    private static String transFormToUtf8(String source) throws Exception{
        return new String(source.getBytes(),"utf-8");
    }
}
